# coding=utf-8
# author:xc
# datetime:2018/8/28 14:24

from . import html
from app import util, upload_files
from dbConnection.MysqlConn import Mysql
from flask import request
from app.MySession import MySession
import time
import MySQLdb, json, base64


# 获取标签
@html.route('/api/poster/tag', methods=['POST', 'GET'])
def api_poster_tag():
    try:
        mysql = Mysql()
        sql = "select tagId,tagName from girl_tag where status=1 order  by addTime desc"
        res = mysql.getAll(sql=sql, param=None)
        mysql.dispose()
        code = util.CODE_EMPTY
        data = []
        if res:
            code = util.CODE_SUCCESS
            data = res
    except Exception as e:
        print e
        data = []
        code = util.CODE_ERROR
    data = {
        'code': code,
        'data': data
    }
    return util.to_json(data)


# 帖子列表
@html.route('/api/poster/list', methods=['POST', 'GET'])
def api_poster_list():
    try:
        session = request.values.get("session", default="0")
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        if str(session) == "0":
            uid = 0
        else:
            uid = MySession.get_name(session)
        mysql = Mysql()
        sql = "select a.*,b.nickname,b.header,c.praise from girl_poster as a left join " \
              "girl_teacher as b on a.uid= b.uid left join (select * from girl_praise " \
              "where uid='%s') as c on a.posterId=c.posterId where a.status=1 order by a.addTime desc limit %d,%d" % (
                  uid, num, util.PAGE_NUM)
        sql1 = "select count(*) from girl_poster  where status=1 "
        sql2 = "select b.*,c.header,c.nickname,d.nickname as name from girl_poster as a " \
               "left join girl_poster_reply as b on a.posterId=b.posterId left join girl_teacher as" \
               " c on b.uid=c.uid left join girl_teacher as d on d.uid=b.f_uid  where " \
               "  b.status=1 order by b.addTime asc "
        result = mysql.getAll(sql, None)
        res = mysql.getAll(sql2, None)
        count = mysql.getOne(sql1, None)
        mysql.dispose()
        data = []
        code = util.CODE_EMPTY
        if count:
            count = count['count(*)']
            if count % util.PAGE_NUM > 0:
                max_page = count / util.PAGE_NUM + 1
            else:
                max_page = count / util.PAGE_NUM
        else:
            max_page = 0
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                data_poster = dict()
                data_poster['posterId'] = x['posterId']
                data_poster['flag'] = x['flag']
                data_poster['content'] = x['content']
                if int(x['flag']) == 0:
                    data_poster['voiceUrl'] = ""
                    data_poster['videoUrl'] = ""
                    data_poster['imgUrl'] = ""
                elif int(x['flag']) == 1:
                    data_poster['voiceUrl'] = ""
                    data_poster['videoUrl'] = ""
                    urls = x['imgUrl'].split(',')
                    url_list = ''
                    for y in urls:
                        if not y.startswith("http"):
                            url_list += upload_files.baseUrl + y + ","
                        else:
                            url_list += y + ","
                    url_list = url_list[:-1]
                    data_poster['imgUrl'] = url_list
                data_poster['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                if x['praise'] is None or int(x['praise']) == 0:
                    data_poster['praise'] = 0
                else:
                    data_poster['praise'] = 1
                if not x['header'].startswith('http'):
                    data_poster['header'] = upload_files.baseUrl + x['header']
                else:
                    data_poster['header'] = x['header']
                data_poster['nickname'] = x['nickname']
                data_poster['praiseNum'] = x['praiseNum']
                reply = []
                if res:
                    for k in res:
                        if x['posterId'] == k['posterId']:
                            data_reply = dict()
                            data_reply['uid'] = k['uid']
                            data_reply['f_uid'] = k['f_uid']
                            if data_reply['f_uid'] == 0:
                                data_reply['name'] = ""
                            else:
                                data_reply['name'] = k['name']
                            data_reply['content'] = k['content']
                            data_reply['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                            data_reply['nickname'] = k['nickname']
                            if not k['header'].startswith("http"):
                                data_reply['header'] = upload_files.baseUrl + k['header']
                            else:
                                data_reply['header'] = k['header']
                            reply.append(data_reply)
                data_poster['res'] = reply
                data.append(data_poster)
    except Exception as e:
        print e
        code = util.CODE_ERROR
        data = []
        max_page = 0
    data = {
        'data': data,
        'code': code,
        'max_page': max_page
    }
    return util.to_json(data)


# 发送帖子
@html.route('/api/send/poster', methods=['POST', 'GET'])
def api_send_poster():
    try:
        code = util.CODE_FAIL
        msg = u'发帖失败'
        res = json.loads(request.data)
        session = res['session']
        if session is None or not MySession.reactive(session):
            data = {
                'code': util.CODE_LOGIN
            }
            return util.to_json(data)
        uid = MySession.get_name(session)
        tagId = res['tagId']
        content = res['content']
        flag = res['flag']
        mysql = Mysql()
        if int(flag) == 1:
            imgUrl = ""
            for x in res['file']:
                url = x['imgBase'].split(',')[1]
                base_img = base64.b64decode(url)
                name = str(time.time()) + '_' + str(19) + '.' + x['imgFormat']
                base = '/tmp_upload/'
                localpath = base + name
                with open(localpath, 'wb') as f:
                    f.write(base_img)
                cdnpath = 'poster/' + name
                result = upload_files.upload_book(localpath, cdnpath)
                if result['status'] == "success":
                    imgUrl += result['url'] + ","
            if imgUrl != "":
                imgUrl = imgUrl[:-1]
            else:
                imgUrl = 0

            sql = "insert into girl_poster(tagId,content,uid,status,flag,imgUrl,addTime,ip) " \
                  "values ('%s','%s','%s',1,'%s','%s',now(),'%s')" % (
                      tagId, content, uid, flag, imgUrl, util.get_current_ip())
            res = mysql.insertOne(sql, None)
            if res > 0:
                msg = u'发帖成功'
                code = util.CODE_SUCCESS
        else:
            sql = "insert into girl_poster(tagId,content,uid,status,flag,addTime,ip) " \
                  "values ('%s','%s','%s',1,'%s',now(),'%s')" % (
                      tagId, content, uid, flag, util.get_current_ip())
            res = mysql.insertOne(sql, None)
            if res > 0:
                msg = u'发帖成功'
                code = util.CODE_SUCCESS
        mysql.dispose()
    except Exception as e:
        print e
        msg = u'服务器内部错误'
        code = util.CODE_ERROR
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# # 帖子回复
@html.route('/api/poster/reply', methods=['POST', 'GET'])
@util.verify_login
def api_post_reply(uid):
    try:
        posterId = request.values.get('posterId')
        f_uid = request.values.get('f_uid', default=0)
        content = request.values.get('content')
        mysql = Mysql()
        sql = "insert into girl_poster_reply(posterId,uid,f_uid,content,addTime,status)" \
              " values('%s','%s','%s','%s',now(),1)" % (
                  posterId, uid, f_uid, MySQLdb.escape_string(content))
        result = mysql.insertOne(sql, None)
        mysql.dispose()
        code = util.CODE_FAIL
        msg = u'回帖失败'
        if result > 0:
            code = util.CODE_SUCCESS
            msg = u'回帖成功'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 帖子点赞或取消赞
@html.route('/api/poster/praise', methods=['POST', 'GET'])
@util.verify_login
def api_poster_praise(uid):
    try:
        posterId = request.values.get('posterId')
        mysql = Mysql()
        code = util.CODE_FAIL
        msg = u"请求失败"
        sql = "select * from girl_praise where uid='%s' and posterId='%s'" % (uid, posterId)
        result = mysql.getOne(sql, None)
        if result:
            if int(result['praise']) == 0:
                sql1 = "update girl_praise set praise=1 where uid='%s' and posterId='%s'" % (uid, posterId)
                res = mysql.update(sql1, None)
                if res > 0:
                    sql2 = "update girl_poster set praiseNum=praiseNum+1 where posterId='%s'" % posterId
                    mysql.update(sql2, None)
                    code = util.CODE_SUCCESS
                    msg = u'点赞成功'
            elif int(result['praise']) == 1:
                sql1 = "update girl_praise set praise=0 where uid='%s' and posterId='%s'" % (uid, posterId)
                res = mysql.update(sql1, None)
                if res > 0:
                    sql2 = "update girl_poster set praiseNum=praiseNum-1 where posterId='%s'" % posterId
                    mysql.update(sql2, None)
                    code = util.CODE_SUCCESS
                    msg = u'取消赞成功'
        else:
            sql1 = "insert into girl_praise(uid,posterId,addTime,praise) VALUES('%s','%s',now(),1)" % (uid, posterId)
            res = mysql.insertOne(sql1, None)
            if res > 0:
                sql2 = "update girl_poster set praiseNum=praiseNum+1 where posterId='%s'" % posterId
                mysql.update(sql2, None)
                code = util.CODE_SUCCESS
                msg = u'点赞成功'
        mysql.dispose()
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)
